import { IoAdapter } from '@nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import Redis from 'ioredis';
import {createClient} from 'redis';
import config from 'src/config';
import { InjectRedis, RedisService } from '@liaoliaots/nestjs-redis';
import { INestApplicationContext } from '@nestjs/common';

export class RedisIoAdapter extends IoAdapter {
	private adapterConstructor: ReturnType<typeof createAdapter>;

	async connectToRedis(): Promise<void> {
		// const pubClient = createClient({ url: `redis://${config.redis.host}:${config.redis.port}` ,password:config.redis.password,database:10});
		const pubClient = new Redis(config.redis).duplicate();
		const subClient = pubClient.duplicate();

		// await Promise.all([pubClient.connect(), subClient.connect()]);
		pubClient.on("error", (err) => {
			console.log(err.message);
		});

		subClient.on("error", (err) => {
			console.log(err.message);
		});
		pubClient.on('connect', () => {
			console.log("pubClient已重新连接");
		});
		subClient.on('connect', () => {
			console.log("subClient已重新连接");
		});
		this.adapterConstructor = createAdapter(pubClient, subClient);
	}

	createIOServer(port: number, options?: ServerOptions): any {
		const server = super.createIOServer(port, options);
		server.adapter(this.adapterConstructor);
		return server;
	}
}
